package com.bbg.amyam.web.flow.service.schoolPublicView.retrievePassword;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import com.bbg.amyam.domain.model.PasswordRetrieveKey;
import com.bbg.amyam.domain.model.Profile;
import com.bbg.amyam.domain.model.School;
import com.bbg.amyam.process.jms.queue.PasswordResetMessage;
import com.bbg.amyam.web.flow.service.WebFlowService;
import com.bbg.amyam.web.flow.service.schoolPublicView.createProfile.CreateProfileForm;
import com.bbg.amyam.web.util.RequestPathParameter;
import com.bbg.amyam.web.util.RequestPathPaser;
import com.bbg.amyam.web.util.StringEncryptor;

@Service("retrievePasswordService")
public class RetrievePasswordServiceImpl extends WebFlowService implements
		RetrievePasswordService {

	private RetrievePasswordForm getForm(RequestContext context) {
		return (RetrievePasswordForm) context.getFlowScope().get(
				"retrievePasswordForm");
	}

	public boolean validateRetrieveKey(RequestContext context,
			String retrieveKey) {

		Long keyId = (Long) context.getFlowScope().get(
				"__password__retrieve__key__id__");
		if (StringUtils.isBlank(retrieveKey) && keyId == null)
			return false;

		if (keyId == null) {
			List<PasswordRetrieveKey> keys = PasswordRetrieveKey
					.findPasswordRetrieveKeysByRetrieveKeyEquals(retrieveKey)
					.getResultList();
			if (keys.size() < 1) {
				return false;
			}
			PasswordRetrieveKey key = keys.get(0);
			context.getFlowScope().put("__password__retrieve__key__id__",
					key.getId());
		}
		return true;
	}

	public Event resetPassword(RequestContext context) {
		RetrievePasswordForm form = getForm(context);
		String newPassword = form.getNewPassword();
		String confirmPassword = form.getConfirmPassword();
		try {
			if (newPassword == null || !newPassword.equals(confirmPassword)) {
				form.setMessage("The confirmed password must be same as new password.");
				form.setNewPassword("");
				form.setConfirmPassword("");
				return error();
			}

			Long id = (Long) context.getFlowScope().get(
					"__password__retrieve__key__id__");
			PasswordRetrieveKey key = PasswordRetrieveKey
					.findPasswordRetrieveKey(id);
			Profile profile = Profile.findProfile(key.getProfileId());

			profile.setPassword(StringEncryptor.encrypte(newPassword));

			profile.merge();
			key.remove();

			return success();
		} catch (Exception e) {
			e.printStackTrace();
			form.setMessage(e.getMessage());
			return error();
		}

	}

}
